<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>简易聊天室</title>
    <style>
        #chat-box { width: 300px; height: 200px; border: 1px solid #000; overflow-y: scroll; padding: 10px; }
        #message { width: 250px; }
    </style>
</head>
<body>
    <h2>聊天室</h2>
    <div id="chat-box"></div>
    <input type="text" id="message" placeholder="输入消息">
    <button onclick="sendMessage()">发送</button>

    <script>
        function fetchMessages() {
            fetch('/chat')
                .then(response => response.text())
                .then(data => {
                    document.getElementById('chat-box').innerText = data;
                });
        }

        function sendMessage() {
            let msg = document.getElementById('message').value;
            fetch('/chat', { method: 'POST', body: msg });
            document.getElementById('message').value = "";
            setTimeout(fetchMessages, 500); // 发送后立即刷新
        }

        setInterval(fetchMessages, 2000); // 每 2 秒请求一次
    </script>
</body>
</html>
